package com.xiaow.springsecuriydemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaow.springsecuriydemo.entity.Role;
import com.xiaow.springsecuriydemo.entity.Roleandperm;
import com.xiaow.springsecuriydemo.entity.User;
import com.xiaow.springsecuriydemo.service.RoleandpermService;
import com.xiaow.springsecuriydemo.service.UserService;
import com.xiaow.springsecuriydemo.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName UserDetailServiceimpl
 * @Author xiaow
 * @DATE 2022/9/15 9:38
 **/
@Service
public class UserDetailServiceimpl implements UserDetailsService {
    @Autowired
    UserService userService;
    @Autowired
    RoleandpermService roleandpermService;

    //    重写SpringSecurity中的查询用户的方法
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", s);
        User one = userService.getOne(userQueryWrapper);
        if (one == null)
            throw new RuntimeException("用户名或密码错误");
        List<Roleandperm> byUserId = roleandpermService.getByUserId(one.getId());
        List<String> list = new LinkedList<>();
        byUserId.forEach(b -> {
            list.add(b.getPerm());
        });
        return new LoginUser(one, list);
    }
}
